package com.youdianstar.app.ui

import android.app.Dialog
import android.graphics.drawable.AnimationDrawable

import android.os.Handler
import android.os.Looper
import android.view.View
import com.youdianstar.app.R
import com.youdianstar.app.BR
import com.youdianstar.app.databinding.ActivityReportSearchBinding
import com.youdianstar.app.common.BisType
import com.youdianstar.app.common.Extra
import com.youdianstar.app.common.base.BaseActivity
import com.youdianstar.app.common.ex.setThrottleListener
import com.youdianstar.app.common.network.BaseApiResultObserver
import com.youdianstar.app.common.util.LogUtil
import com.youdianstar.app.util.AppDialogUtil
import com.youdianstar.app.common.auko.startActivity

import org.koin.androidx.viewmodel.ext.android.viewModel


/**
 * File: ReportSearchActivity
 * Author: 82149 Create: 2021/11/18 18:46
 * Changes (from 2021/11/18)
 * --------------------------------------------------
 * description:
 * ---------------------------------------------------
 *
 */
class ReportSearchActivity : BaseActivity<ActivityReportSearchBinding, ReportViewModel>() {
    override fun layoutId(): Int = R.layout.activity_report_search

    override fun initVariableId(): Int = BR.viewModel

    override fun initViewModel(): ReportViewModel {
        val model: ReportViewModel by viewModel()
        return model
    }

    private val mHandler = Handler(Looper.myLooper()!!)
    //业务类型 1 充电宝不弹出 2 充电宝归还不结束
    private var bisType = 0
    private var orderNo = ""
    private var penaltyAmount = 0.0F

    private var titleStr: String = ""
    private var desStr: String = ""
    //Pb 是否找到
    private var isFoundPb = false
    private var tagCount = 0 //接口请求次数,Max 5
    private var resultDialog: Dialog?=null


    override fun initData() {
        super.initData()
        val order = intent.getStringExtra(Extra.IT_ORDERNO)
        order?.let {
            orderNo = it
        }

        bisType = intent.getIntExtra(Extra.IT_TYPE, BisType.Report_RentFailed)
        penaltyAmount = intent.getFloatExtra(Extra.IT_MONEY,0F)

        titleStr = if (bisType == BisType.Report_RentFailed)
            getString(R.string.home_failedEject)
        else
            getString(R.string.home_orderDidNotEnd)

        desStr = if (bisType == BisType.Report_RentFailed)
            getString(R.string.home_confirmPBNotEject)
        else
            getString(R.string.home_confirmPBIn)

        resetLayout(false)
    }


    override fun initClickEvent() {
        mBinding.btnConfirm.setThrottleListener {
            startSearchAction()
        }
    }

    override fun initLiveObserver() {
        super.initLiveObserver()
        mViewModel.reportBeforeLiveData.observe(this, object : BaseApiResultObserver<com.youdianstar.app.entity.ReportBefore>(false) {
                override fun onDataResult(data: com.youdianstar.app.entity.ReportBefore?) {
                    super.onDataResult(data)
                    data?.let {
                        isFoundPb = it.isInCabinet
                    }
                    tagCount ++
                    if (isFoundPb || tagCount>=5){
                        //显示轮询结果
                        mHandler.removeCallbacksAndMessages(null)
                        mHandler.postDelayed({
                            resetLayout(false, isVisBtn = false)//cleanAnim()
                            showFoundResultDialog()
                        }, 2000L)
                    }else{
                        //延时5秒再查下一次
                        mHandler.postDelayed({
                            mViewModel.reportBeforeCheck(orderNo)
                        }, 5000L)
                    }
                }

                override fun onNetError(code: Int, e: String?) {
                    super.onNetError(code, e)
                    tagCount ++
                    if (tagCount>=5)
                        resetLayout(false, isVisBtn = true)
                    else{
                        //延时5秒再查下一次
                        mHandler.postDelayed({
                            mViewModel.reportBeforeCheck(orderNo)
                        }, 5000L)
                    }
                }
            })
    }

    private fun resetLayout(isSearch:Boolean,isVisBtn :Boolean = true) {
        if (isSearch){
            mBinding.headBar.initTitle(this, getString(R.string.home_searchingPB), showInner = false)
            mBinding.headBar.setBackUnable(false)
            mBinding.tvContent.text = getString(R.string.home_searchingPBText)
            mBinding.btnConfirm.visibility = View.INVISIBLE
        }else{
            mBinding.headBar.initTitle(this, titleStr, showInner = false)
            mBinding.headBar.setBackUnable(true)
            mBinding.tvContent.text = desStr
            mBinding.btnConfirm.visibility = if (isVisBtn)View.VISIBLE else View.INVISIBLE
            cleanAnim()
            initSearchAnim()
        }
    }

    /**开始搜索动画*/
    private fun startSearchAction(){
        isFoundPb = false //初始查询
        tagCount = 1
        //调用接口 检查
        mViewModel.reportBeforeCheck(orderNo)
        resetLayout(true)
        mBinding.ivAnimSearch.visibility = View.INVISIBLE
        mBinding.ivAnimFrame.visibility = View.VISIBLE
        //开启动画
        startSearchAnim()
    }

    private fun startResultAction(){
        if (isFoundPb) {
            dismissFoundDialog()
            startActivity<OrderDetailActivity>(Extra.IT_ORDERNO to orderNo)
            overridePendingTransition(0, android.R.anim.slide_out_right)
            finish()
        } else {
            startActivity<ReportOrderActivity>(
                Extra.IT_TYPE to bisType,
                Extra.IT_ORDERNO to orderNo,
                Extra.IT_MONEY to penaltyAmount
            )
            overridePendingTransition(0, android.R.anim.slide_out_right)
        }
    }

    private fun initSearchAnim() {
        mBinding.ivAnimSearch.visibility = View.VISIBLE
        mBinding.ivAnimFrame.visibility = View.INVISIBLE
    }

    private fun startSearchAnim() {
        LogUtil.i("---Frame anim start")
        (mBinding.ivAnimFrame.background as AnimationDrawable).start()
    }

    private fun cleanAnim() {
        LogUtil.i("---Frame anim stop")
        (mBinding.ivAnimFrame.background as AnimationDrawable).stop()
    }

    /**显示结果弹框*/
    private fun showFoundResultDialog(){
        dismissFoundDialog()
        if (this.isFinishing)
            return
        val contentTx = if (isFoundPb) getString(R.string.home_pbFoundResult) else getString(R.string.home_unfindPB)
        val leftTx = if (isFoundPb) getString(R.string.order_homePage) else getString(R.string.home_recheck)
        val rightTx = if (isFoundPb) getString(R.string.home_viewOrder) else getString(R.string.home_reportIssue)
        resultDialog = AppDialogUtil.instance.showSearchResultDialog(this, title = "", msg = contentTx,
            leftAction = {
                dismissFoundDialog()
                if (isFoundPb){
                    finish()
                }else{
                    startSearchAction()
                }
            }, rightAction = {
                startResultAction()
            },leftTx,rightTx)
    }

    private fun dismissFoundDialog(){
        resultDialog?.dismiss()
    }

    override fun onDestroy() {
        mHandler.removeCallbacksAndMessages(null)
        cleanAnim()
        dismissFoundDialog()
        super.onDestroy()
    }
}